package com.example.upload.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {
    String path = "C:\\Users\\zhangtengfei\\Desktop\\upload\\src\\main\\resources\\static\\upload\\";

    @PostMapping("/upload")
    public Map<String,Object> upload(MultipartFile file,Integer index,String md5,Integer status,String type) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        //status 上传状态,0: 正在继续分片上传,1 最后一片上传
        String s = path + md5;
        Path filePath = Paths.get(s);
        File orgFile = new File(s);
        File file_ok = new File(s+"."+type);
        byte[] bytes = file.getBytes();
        if (orgFile.exists()){
            // 文件追加 Nio
            Files.write(filePath,bytes, StandardOpenOption.APPEND);
        }else {
            Files.write(filePath,bytes, StandardOpenOption.CREATE_NEW);
        }
        if (status==1 && orgFile.exists()){
            orgFile.renameTo(file_ok);
        }
        map.put("code",0);
        return map;
    }

    /**
     * 是否秒传
     * @param md5
     * @param type
     * @return
     */
    @GetMapping("/isSecon")
    public Map<String,Object> isSecon(String md5,String type){
        String s = path + md5;
        File file = new File(s + "." + type);
        HashMap<String, Object> map = new HashMap<>();
        if (file.exists()){
            map.put("code",0);
            map.put("data",-1);
            map.put("mgs","秒传成功");
            return map;
        }
        file = new File(s);
        if (file.exists()){
            // 说明是断点续传
            map.put("code",1);
            map.put("data",file.length());
        }else {
            map.put("code",1);
            map.put("data",0);
        }
        return map;
    }


    @GetMapping("/test")
    public Map test(){
        HashMap hashMap = new HashMap();
        hashMap.put("ztf","ztf");
        return hashMap;
    }
}
